package fsmi.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import fsmi.daoservice.CourseDAO;
import fsmi.model.CourseBean;
import fsmi.model.CourseListBean;

public class CourseDB implements CourseDAO {

	private PreparedStatement stmt;
	private Connection conn;
	private DBPool pool;

	public CourseDB() {
		pool = DBPool.getInstance();
		if (pool.getConnCount() != 0) {
			conn = pool.getConn();
		}
	}

	@Override
	public CourseListBean getCourse(String stuID) {
		// TODO Auto-generated method stub
		String sql = "select c.cid,c.cname from Course c,Joint j where c.cid=j.cid and j.sid=?;";
		try {
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, stuID);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultSet result = null;
		List<CourseBean> courses = new LinkedList<CourseBean>();
		try {
			result = stmt.executeQuery();
			while (result.next()) {
				String cid = result.getString("cid");
				String cname = result.getString("cname");
				CourseBean c = new CourseBean();
				c.setCid(cid);
				c.setCname(cname);
				courses.add(c);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		CourseListBean list = new CourseListBean();
		list.setCourseList(courses);
		return list;
	}

	public void destroyUserCourseDB() {
		try {
			stmt.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		stmt = null;
		pool.returnConn(conn);
		conn = null;
		pool = null;
	}

}
